# from rest_framework import request
from rest_framework.views import APIView  # 继承了Django的view
from django.http import HttpResponse, JsonResponse
from api.user.models import UserInfo, UserToken
from crm.http_config import API_TEMPLATE, HttpCode
import uuid


class AuthView(APIView):

    def get(self, request, *args, **kwargs):
        """查询用户列表"""
        res = API_TEMPLATE.copy()
        try:
            users = UserInfo.objects.all().values()
            print(users)
            res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1], data=str(users))
            return JsonResponse(res)
        except Exception as e:
            res.update(code=HttpCode.authentication_error.value[0], msg=HttpCode.authentication_error.value[1])
            return JsonResponse(res)

    def post(self, request, *args, **kwargs):
        """用户登录"""
        res = API_TEMPLATE.copy()
        try:
            username = request.POST.get("username")
            password = request.POST.get("password")
            user = UserInfo.objects.filter(username=username, password=password).first()
            if not user:
                res.update(code=HttpCode.authentication_error.value[0], msg=HttpCode.authentication_error.value[1])
                return JsonResponse(res)
            uid = str(uuid.uuid4())
            UserToken.objects.update_or_create(user=user, defaults={'token': uid})
            res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1])
            return JsonResponse(res)
        except Exception as e:
            print(e)
            res.update(code=HttpCode.internal_error.value[0], msg=HttpCode.internal_error.value[1])
            return JsonResponse(res)

    def put(self, request, *args, **kwargs):
        """更新用户"""
        return HttpResponse("put")

    def delete(self, request, *args, **kwargs):
        """删除用户"""
        return HttpResponse("delete")


class OrderView(APIView):

    def get(self, request, *args, **kwargs):
        return HttpResponse("get")

    def post(self, request, *args, **kwargs):
        return HttpResponse("post")

    def put(self, request, *args, **kwargs):
        return HttpResponse("put")

    def delete(self, request, *args, **kwargs):
        return HttpResponse("delete")


from rest_framework.parsers import JSONParser, FormParser


class DjangoView(APIView):
    # JSONParser处理Content-Type:application/json
    # FormParser处理Content-Type:application/x-www-form-urlencoded
    parser_classes = [JSONParser, FormParser]  # 允许用户发json数据

    def post(self, request, *args, **kwargs):
        print(request.data)

        return HttpResponse("django")

    def get(self, request, *args, **kwargs):
        return HttpResponse("django")


# # django 处理 queryset
# from api.user.models import Role
# import json
#
#
# class RolesView(APIView):
#
#     def get(self, request, *args, **kwargs):
#         res = API_TEMPLATE.copy()
#         data = Role.objects.all().values('id', 'title')
#         roles = list(data)
#         ret = json.dumps(roles, ensure_ascii=False)
#         res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1], data=ret)
#         return JsonResponse(res)

# drf处理queryset
from api.user.models import Role
from rest_framework import serializers
import json


class RolesSerializers(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField()


class RolesView(APIView):

    def get(self, request, *args, **kwargs):
        res = API_TEMPLATE.copy()

        # # 多个数据many=True
        # roles = Role.objects.all()
        # ser = RolesSerializers(instance=roles, many=True)
        # ret = json.dumps(ser.data, ensure_ascii=False)
        # 一个数据many=False
        roles = Role.objects.first()
        ser = RolesSerializers(instance=roles, many=False)
        ret = json.dumps(ser.data, ensure_ascii=False)

        res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1], data=ret)
        return JsonResponse(res)


from api.user.models import UserInfo


class UserInfoSerializer2(serializers.Serializer):
    # 枚举choices的处理
    # user_type = serializers.CharField(source="user_type")  # source会关联查询数据
    user_type = serializers.CharField(source="get_user_type_display")
    username = serializers.CharField()
    password = serializers.CharField()

    # 外键的处理
    group = serializers.CharField(source="group.title")

    # 多对多的显示 SerializerMethodField 自定义显示 get_rls()
    rls = serializers.SerializerMethodField()

    def get_rls(self, row):
        # get_+字段名称
        role_obj_list = row.roles.all()
        ret = []
        for item in role_obj_list:
            ret.append({"id": item.id, "title": item.title})
        return ret


class UserInfoSerializer(serializers.Serializer):
    # 枚举choices的处理
    group = serializers.HyperlinkedIdentityField(view_name="gp", lookup_field="group_id", lookup_url_kwarg="pk")

    class meta:
        model = UserInfo
        fields = "__all__"  # 显示全部
        # fields = ["id","username","password","group","roles"]


class UserinfoView(APIView):
    def get(self, request, *args, **kwargs):
        res = API_TEMPLATE.copy()
        users = UserInfo.objects.all()
        ser = UserInfoSerializer(instance=users, many=True, context={"request": request})
        ret = json.dumps(ser.data, ensure_ascii=False)
        res.update(code=HttpCode.ok.value[0], msg=HttpCode.ok.value[1], data=ret)
        return JsonResponse(res)


from api.user.models import UserGroup


class GroupSerializer(serializers.Serializer):
    # 枚举choices的处理
    class meta:
        model = UserGroup
        fields = "__all__"


class GroupView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        obj = UserGroup.objects.filter(pk=pk).first()
        ser = GroupSerializer(instance=obj, many=False)
        ret = json.dumps(ser.data, ensure_ascii=False)
        return HttpResponse(ret)


####################    数据验证    #########################
class TitleValidator(object):
    """自定义验证规则"""

    def __init__(self, base):
        self.base = str(base)

    def __call__(self, value):
        if not value.startswith(self.base):
            message = "this field must start with %s" % self.base
            raise serializers.ValidationError(message)

    def set_context(self, serializer_field):
        pass


class UsergroupSerializer(serializers.Serializer):
    title = serializers.CharField(error_messages={"required": "标题不能为空"}, validators=[TitleValidator("老男孩")])


class UsergroupView(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        # data 要验证的数据
        # validators 自定义验证规则
        ser = UsergroupSerializer(data=request.data)
        if ser.is_valid():
            print(ser.validated_data)
            return HttpResponse(ser.validated_data)
        else:
            print(ser.errors)
            return HttpResponse(ser.errors)


####################    数据验证    #########################

####################    数据分页    #########################
from api.order.utils.serializers.pages import PagerSerializer
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination


class MyLimitPagination(LimitOffsetPagination):
    """在某个位置 向后查询多少条数据"""
    # 从第几条开始
    offset_query_param = 'offset'
    # 显示几个
    limit_query_param = 'limit'
    # 默认显示2个
    default_limit = 2
    # 最多显示10个
    max_limit = 10


class MyPagination(PageNumberPagination):
    """看第几页 每页显示多少数据"""
    # url中转换分页的参数
    page_query_param = "page"
    # 定制显示几个
    page_size_query_param = "size"
    # 每页显示几个
    page_size = 2
    # 最多显示几个
    max_page_size = 5


class MyCursorPagination(CursorPagination):
    # url参数
    cursor_query_param = 'cursor'
    # 默认排序规则
    ordering = '-created'
    # 每页显示几个
    page_size = 2
    # 每页最多显示几个
    max_page_size = 5
    # 定制size
    page_size_query_param = None


class Pager1View(APIView):
    def get(self, request, *args, **kwargs):
        # 获取所有数据
        roles = Role.objects.all()
        # 创建分页对象
        # pg = MyPagination()
        # pg = MyLimitPagination()
        pg = MyCursorPagination()

        # 对数据分页
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 序列化
        ser = PagerSerializer(instance=pager_roles, many=True)
        # return Response(ser.data)
        return pg.get_paginated_response(ser.data)


####################    数据分页    #########################

####################    其他视图    #########################

from rest_framework.generics import GenericAPIView

# class v1View(GenericAPIView):
#     """
#     url:/api/v1/user/v1view
#     """
#     queryset = Role.objects.all()
#     serializer_class = PagerSerializer
#     pagination_class = PageNumberPagination
#
#     def get(self, request, *args, **kwargs):
#         # 获取数据
#         roles = self.get_queryset()
#         # 分页
#         pager_roles = self.paginate_queryset(roles)
#         # 序列化
#         self.get_serializer(instance=pager_roles, many=True)
#         return Response("111")
from rest_framework.viewsets import GenericViewSet


# class v1View(GenericViewSet):
#     """
#     可以修改get和post的方法名称
#     """
#     queryset = Role.objects.all()
#     serializer_class = PagerSerializer
#     pagination_class = PageNumberPagination
#
#     def get(self, request, *args, **kwargs):
#         # 获取数据
#         roles = self.get_queryset()
#         # 分页
#         pager_roles = self.paginate_queryset(roles)
#         # 序列化
#         self.get_serializer(instance=pager_roles, many=True)
#         return Response("111")


from rest_framework.viewsets import ModelViewSet
from rest_framework.mixins import ListModelMixin, UpdateModelMixin, CreateModelMixin, DestroyModelMixin
class v1View(ModelViewSet):
    """
    可以修改get和post的方法名称
    """
    queryset = Role.objects.all()
    serializer_class = PagerSerializer
    pagination_class = PageNumberPagination

    def get(self, request, *args, **kwargs):
        # 获取数据
        roles = self.get_queryset()
        # 分页
        pager_roles = self.paginate_queryset(roles)
        # 序列化
        self.get_serializer(instance=pager_roles, many=True)
        return Response("111")

####################    其他视图    #########################
####################    渲染    #########################
from rest_framework.renderers import AdminRenderer,JSONRenderer,BrowsableAPIRenderer,HTMLFormRenderer
####################    渲染    #########################